package com.chd.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chd.dto.Result;
import com.chd.entity.Shop;
import com.chd.mapper.ShopMapper;
import com.chd.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chd.utils.CacheClient;
import com.chd.utils.CountingBloomFilter;
import com.chd.utils.RedisData;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.chd.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Resource
    private CountingBloomFilter countingBloomFilter;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    @CacheEvict(value = "shop", key= "#id")
    public Result queryById(Long id) {
        // 缓存穿透
//        Shop shop = cacheClient
//                .queryWithPassThrough(CACHE_SHOP_KEY,
//                        id,
//                        Shop.class,
//                        this::getById,
//                        CACHE_SHOP_TTL,
//                        TimeUnit.MINUTES);

//        Shop shop = queryWithPassThrough(id);

        // 互斥锁解决缓存穿透
//        Shop shop = queryWithMutex(id);

        // 逻辑过期解决缓存击穿
        Shop shop = cacheClient
                        .queryWithLogicalExpire(CACHE_SHOP_KEY,
                                id,
                                Shop.class,
                                this::getById,
                                CACHE_SHOP_TTL,
                                TimeUnit.MINUTES);

        // 返回结果
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    public Shop queryWithMutex(Long id){
        String key = CACHE_SHOP_KEY + id;

        // 0. 计数布隆过滤器查询
        if (!countingBloomFilter.mightContain(key)) {
            return null;
        }
        // 1. 从Redis中查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2. 判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 3. 存在, 直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 4. 实现缓存重建
        //   4.1 获取互斥锁
        Shop shop;
        String lock_key = LOCK_SHOP_KEY + id;
        try {
            while (!tryLock(lock_key)) {
                Thread.sleep(50);
            }
            shop = getById(id);
            // 5. 不存在, 返回错误
            if (shop == null) {
                return null;
            }
            // 6. 存在, 写入 Redis
//            Thread.sleep(100);
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(lock_key);
        }
        // 7. 返回
        return shop;
    }

    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    private void saveShop2Redis(Long id, Long expireSeconds) {
        Shop shop = getById(id);

        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));

        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));

    }

    public Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;

        // 0. 计数布隆过滤器查询
        if (!countingBloomFilter.mightContain(key)) {
            return null;
        }
        // 1. 从Redis中查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2. 判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 3. 存在, 直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 4. 不存在, 根据 ID 查询数据库
        Shop shop = getById(id);
        // 5. 不存在, 返回错误
        if (shop == null) {
            return null;
        }
        // 6. 存在, 写入 Redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 7. 返回
        return shop;
    }


    // 逻辑过期解决缓存击穿问题
    public Shop queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;

        // 0. 计数布隆过滤器查询
        if (!countingBloomFilter.mightContain(key)) {
            return null;
        }
        // 1. 从Redis中查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2. 判断是否存在
        if (StrUtil.isBlank(shopJson)) {
            // 3. 存在, 直接返回
            return null;
        }
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();

        if (expireTime.isAfter(LocalDateTime.now())) {
            return shop;
        }

        String lockKey = LOCK_SHOP_KEY + id;
        try {
            while (!tryLock(lockKey)) {
                Thread.sleep(50);
            };
            CACHE_REBUILD_EXECUTOR.submit(() -> {
               this.saveShop2Redis(id, 20L);
            });

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(lockKey);
        }


        // 7. 返回
        return shop;
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺ID为空");
        }
        updateById(shop);
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }
}
